package edu.shzu.manage.controller;

import edu.shzu.manage.entity.Menu;
import edu.shzu.manage.service.MenuServie;
import edu.shzu.manage.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
public class MenuController {
    @Autowired
    MenuServie menuServie;

    @GetMapping("/menu")
    public Result getMenuById(Integer id) {
        Menu resultMenu = menuServie.getMenuById(id);
        if (resultMenu != null) {
            System.out.println(resultMenu);
            return Result.success(resultMenu);
        } else {
            return Result.fail();
        }
    }

    @GetMapping("/menus/query")
    public Result queryMenu(String str) {
        List<Menu> menuList = menuServie.queryMenu(str);
        if (menuList.size() > 0) {
            return Result.success(menuList);
        } else {
            return Result.fail();
        }
    }

    /**
     * 新增菜单权限
     * @return
     */
    @PostMapping("/menu/insert")
    public Result insertMenu(@RequestBody Menu menu){
        int i = menuServie.insertMenu(menu);
        if (i > 0) {
            return Result.success();
        } else {
            return Result.error(3011,"添加菜单失败");
        }
    }

    /**
     * 根据Id 更新菜单权限
     * @param menu
     * @return
     */
    @PutMapping("/menu/update")
    @Transactional
    public Result updateMenu(@RequestBody Menu menu){
        int i = menuServie.updateMenu(menu);
        if (i > 0) {
            return Result.success();
        } else {
            return Result.error(3012,"更新菜单失败");
        }

    }

    /**
     * 根据Id 删除菜单权限
     * @param menuId
     * @return
     */
    @DeleteMapping("menu/{id}")
    public Result deleteMenu(@PathVariable("id") Integer menuId) {
        int i = menuServie.deleteMenu(menuId);
        if (i > 0) {
            return Result.success();
        } else {
            return Result.error(3013,"删除菜单失败");
        }
    }

    /**
     * 树形菜单
     * @return
     */
    @GetMapping("/menu/tree")
    public Result getTree() {
        List<Menu> menuList  = menuServie.getAllMenu();
        if (menuList.size() > 0) {
            return Result.success(menuList);
        } else {
            return Result.fail();
        }
    }
}
